<template>
  <div id="QiRpt">
    <Breadcrumb content="指标维护" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="19">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" :loading="showLoading" @click="findQiMajorList"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-square-plus" class="button-blue" content="新增" @click="handleAdd(-1)"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-save" class="button-blue" content="保存" @click="saveList"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="qiRptTableBox">
            <vxe-table ref="qiMajorTableRef" :loading="showLoading" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="qiMajorList" @cell-click="rptRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" :edit-config="{
                trigger: 'click',
                mode: 'row',
                showIcon: true
              }" resizable show-overflow>
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column field="majorCode" title="编码" width="60px" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.majorCode" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="majorName" title="名称"  :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.majorName" type="text"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="81">
          <el-tabs type="border-card" @tab-click="tabHandleClick">
            <el-tab-pane label="指标项目同步">
              <Splitpanes horizontal>
                <Pane size="60">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="同步数据" :loading="syncLoading" @click="syncData()"></vxe-button>
                      <div class="msgDiv">双击项目移除对应关系</div>
                    </template>
                  </vxe-toolbar>
                  <div class="qiRptFiledTable">
                    <vxe-table ref="qiRptFiledTableRef" :loading="showLoading" class="mytable-scrollbar" align="left" border height="auto" :keep-source="true" :data="qiIndexIMainList"  :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true }"  resizable show-overflow @cell-dblclick="deleteQiIndexIMain">
                      <vxe-column type="checkbox" align="center" width="26"></vxe-column>
                      <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
                      <vxe-column field="itemCode" title="项目编码" min-width="80px">
                      </vxe-column>
                      <vxe-column field="itemName" title="项目名称" width="820px"></vxe-column>
                    </vxe-table>
                  </div>
                </Pane>
                <Pane size="40">
                  <vxe-table ref="qiRptFiledTableFilterRef" :loading="showLoading" class="mytable-scrollbar" align="left" border height="auto" :keep-source="true" :data="qiIndexIMainFilterList"  :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true }"  resizable show-overflow @cell-dblclick="deleteQiIndexIMainFilter">
                    <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
                    <vxe-column field="itemCode" title="项目编码" min-width="80px">
                    </vxe-column>
                    <vxe-column field="itemName" title="项目名称" width="820px"></vxe-column>
                  </vxe-table>
                </Pane>
              </Splitpanes>
            </el-tab-pane>
            <el-tab-pane v-for="item in departList" :key="item.moduleType" :label="item.moduleName" :name="item.moduleType" >
              <Splitpanes>
                <Pane size="30">
                  <div class="leftTable" style="height: 100%">
                    <vxe-table ref="feeitemVsItemdictTable" border class="mytable-scrollbar" height="auto" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" :data="qiIndexSqlBusinessList" :loading="showLoading" @cell-dblclick="deleteQiIndexSqlBusinessList">
                      <vxe-column type="seq" title="序号" width="50"></vxe-column>
                      <vxe-column field="businessValue" title="业务值"></vxe-column>
                      <vxe-column field="businessNa" title="业务说明"></vxe-column>
                    </vxe-table>
                  </div>
                </Pane>
                <Pane size="70">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <vxe-input v-model="searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getBusinessModuleAndData" @search-click="getBusinessModuleAndData()" @keyup="keyupEnter"></vxe-input>
                      <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="getBusinessModuleAndData"></vxe-button>
                    </template>
                  </vxe-toolbar>
                  <vxe-table ref="detailTable" class="mytable-scrollbar" border align="center" height="auto" :data="tableDataList" @cell-dblclick="tableDataRowClick" :loading="tpLoading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                    <vxe-column v-for="(item, index) in tableFieldList" :key="index" :field="item.columnName" :title="item.comments" :edit-render="{}"> </vxe-column>
                  </vxe-table>
                </Pane>
              </Splitpanes>
            </el-tab-pane>

          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let showLoading = ref(false); //左侧刷新+表格加载状态
let syncLoading = ref(false); //同步数据
interface RowVO {
  id: string;
  majorCode: string;
  majorName: string;
  inputCode: string;
  seq: number;
}
// 报表列表
const qiMajorList = reactive([]);
const qiIndexIMainList = reactive([]);
const qiIndexIMainFilterList = reactive([]);
let searchValue = ref('');
const qiMajorTableRef = ref(null);
const reportTemplateList = reactive([]); //报表模板列表
let departList: any = reactive([]); //部门列表数据
let tableFieldList: any = reactive([]); //设计模式表格数据
let tableDataList: any = reactive([]); //预览模式表格数据
let businessModuleList: any = reactive([]);
let tpLoading = ref(false); //预览模式 刷新+表格
let selevctBarCodeRow :any = reactive({
  id: ''
});
// 方法定义区 =============
onMounted(() => {
  findQiMajorList();
  findModuleList();
  getDictMeasureList();
  getBusinessModuleList();
});

// 获取左侧表格数据
function findQiMajorList() {
  showLoading.value = true;
  qiMajorList.length = 0; //放入数据前清空数据
  const url = '/api/qi/major/getQiMajorList';
  proxy.$http
      //注意此处的数据条数
      .get(url)
      .then((res: any) => {
        if (!IsEmpty(res.data)) {
          qiMajorList.push(...res.data);
          if (qiMajorList.length > 0) {
            rptRowClick({ row: qiMajorList[0] });
          }else {
            qiIndexSqlBusinessList.length=0;
          }
        }
        showLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        showLoading.value = false;
      });
}
// 获取部门列表
function findModuleList() {
  showLoading.value = true;
  departList.length = 0;

  const url = '/api/qi/qiIndexBusinessModule/findBusinessModules';
  proxy.$http
      .get(url)
      .then((res: any) => {
        departList.push(...res.data);
        if (departList.length > 0) {
          for (const item of departList) {
            item.showFieldes = [];
            if (!IsEmpty(item.showFields)) {
              item.showFieldes = item.showFields.split(',');
            }
          }
        }

        showLoading.value = false;
      })
      .catch((err: any) => {
        showLoading.value = false;
      });
}
async function getBusinessModuleList() {
  const url = '/api/qi/qiIndexBusinessModule/findBusinessModules';
  const businessModules: any = await proxy.$http.get(url);
  businessModuleList.push(...businessModules.data);
}

// 点击当前行// 行点击事件
function rptRowClick({ row }: any) {
  (proxy.$refs.qiMajorTableRef as any).setCurrentRow(row);
  selevctBarCodeRow = row;
  getQiIndexSqlBusinessList();
  findqiIndexIMainList();
  findqiIndexIMainFilterList();
}

// 添加
async function handleAdd(row?: RowVO | number) {
  const $table = qiMajorTableRef.value;
  if ($table) {
    const record = {
      id: null,
      dataSource: '1',
      majorCode: '',
      majorName: '',
      indexType: '',
      reportTemplateId: '',
      seq: ''
    };
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditRow(newRow);
    $table.setCurrentRow(newRow);
  }
}

//批量保存
function saveList() {
  const $xTable = proxy.$refs.qiMajorTableRef as any;
  const arrModifies = $xTable.getUpdateRecords();
  const arrNews = $xTable.getInsertRecords();
  arrNews.forEach((item: any, idx) => {
    const url = '/api/qi/major/addQiMajor';
    const data = item;
    proxy.$http
        .post(url, data)
        .then((res: any) => {
          if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
            VxeMessage('保存成功', VxeNotifyType.success);
            findQiMajorList();
          }
        })
        .catch((err) => {
          if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
            VxeMessage(err, VxeNotifyType.error);
          }
        });
  });
  arrModifies.forEach((item, idx) => {
    const url = '/api/qi/major/updateQiMajor';
    const data = item;
    proxy.$http
        .post(url, data)
        .then((res: any) => {
          if (idx === arrModifies.length - 1) {
            VxeMessage('保存成功', VxeNotifyType.success);
            findQiMajorList();
          }
        })
        .catch((err) => {
          if (idx === arrModifies.length - 1) {
            VxeMessage(err, VxeNotifyType.error);
          }
        });
  });
}

// 删除
function handleDelete() {
  const $xTable = proxy.$refs.qiMajorTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
      .$confirm('确定删除此项？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then((type) => {
        if (type === 'confirm') {
          selectRows.forEach((item, idx) => {
            const url = '/api/qi/major/deleteQiMajor';
            proxy.$http
                .post(url, item)
                .then((res: any) => {
                  if (idx === selectRows.length - 1) {
                    VxeMessage('删除成功', VxeNotifyType.success);
                    findQiMajorList();
                  }
                })
                .catch((err) => {
                  VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
                });
          });
        }
      });
}
//获取报表模板列表
function getDictMeasureList() {
  reportTemplateList.length = 0;
  const url = '/api/pubReport/getReportList';
  proxy.$http
      .get(url, { params: { pageIndex: 1, pageSize: 50 ,type:1,code:'20240703001'} })
      .then((res: any) => {
        reportTemplateList.push(...res.data.reportList.records);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
  console.log('reportTemplateList',reportTemplateList)
}

let sltBusinessModule = null;
let sltModuleType = null;

function tabHandleClick(tab) {
  if (tab.index >= 1) {
    sltModuleType = tab.props.name;
    getBusinessModuleAndData();
    getQiIndexSqlBusinessList();
  }
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getBusinessModuleAndData();
  }
}

function getBusinessModuleAndData() {
  //根据moduleType 查出表 及表数据
  tableFieldList.length = 0;
  tableDataList.length = 0;
  tpLoading.value = true;
  sltBusinessModule = businessModuleList.find((m) => m.moduleType == sltModuleType);
  const url = '/api/qi/qiIndexBusinessModule/getMajorModuleAndData';
  proxy.$http
      .get(url, {
        params: {
          moduleType: sltModuleType,
          keywords: searchValue.value
        }
      })
      .then((res: any) => {
        if (res.status.code === 1) {
          tableFieldList.push(...res.data.tableFieldList);
          tableDataList.push(...res.data.tableDataList);
        } else {
          VxeMessage('获取列表失败', VxeNotifyType.error);
        }
        tpLoading.value = false;
      })
      .catch((err: any) => {
        tpLoading.value = false;
        VxeMessage(err, VxeNotifyType.error);
      });
}

let qiIndexSqlBusinessList = reactive([]);
function getQiIndexSqlBusinessList() {
  qiIndexSqlBusinessList.length = 0;
  const url = '/api/qi/majorBusiness/findQiMajorBusinessList';
  const data = {
    params: {
      moduleType: sltModuleType,
      majorCode: selevctBarCodeRow.majorCode
    }
  };
  proxy.$http
      .get(url, data)
      .then((res: any) => {
        qiIndexSqlBusinessList.push(...res.data);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

// 双击中间列表删除数据
function deleteQiIndexSqlBusinessList({ row }: any) {
  const url = '/api/qi/majorBusiness/deleteQiMajorBusiness';
  proxy.$http
      .post(url, row)
      .then((res: any) => {
        getQiIndexSqlBusinessList();
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
}

function tableDataRowClick({ row }: any) {
  if (IsEmpty(selevctBarCodeRow.majorCode)){
    VxeMessage('请先选中左侧编码', VxeNotifyType.warning);
    return;
  }
  const url = '/api/qi/majorBusiness/addQiMajorBusiness';
  let labFeeitemVsItemDict = {
    businessValue: row[sltBusinessModule.outField],
    businessNa: row[sltBusinessModule.showField],
    moduleType: sltBusinessModule.moduleType,
    majorCode: selevctBarCodeRow.majorCode
  };
  proxy.$http
      .post(url, labFeeitemVsItemDict)
      .then((res: any) => {
        getQiIndexSqlBusinessList();
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

// 获取列表
function findqiIndexIMainList() {
  if (IsEmpty(selevctBarCodeRow.majorCode)){
    return;
  }
  showLoading.value = true;
  const url = '/api/qi/reportFiled/getQiIndexItemListByMajorCode/' + selevctBarCodeRow.majorCode;
  qiIndexIMainList.length = 0; //放入数据前清空数据
  proxy.$http
      .get(url)
      .then((res: any) => {
        if (!IsEmpty(res.data)) {
          qiIndexIMainList.push(...res.data);
        }
        proxy.$nextTick(() => {
          proxy.$refs.qiRptFiledTableRef.setAllCheckboxRow(true);
        })
        showLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        showLoading.value = false;
      });
}
// 获取列表
function findqiIndexIMainFilterList() {
  if (IsEmpty(selevctBarCodeRow.majorCode)){
    return;
  }
  showLoading.value = true;
  const url = '/api/qi/reportFiled/getQiIndexItemFilterListByMajorCode/' + selevctBarCodeRow.majorCode;
  qiIndexIMainFilterList.length = 0; //放入数据前清空数据
  proxy.$http
      .get(url)
      .then((res: any) => {
        if (!IsEmpty(res.data)) {
          qiIndexIMainFilterList.push(...res.data);
        }
        showLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        showLoading.value = false;
      });
}
// 移除项目
function deleteQiIndexIMain({ row }: any) {
  const url = '/api/qi/reportFiled/addQiIndexItemFilter';
  proxy.$http
      .post(url, {
        id: row.id,
        majorCode: selevctBarCodeRow.majorCode,
        indexId: row.indexId,
        indexCode: row.indexCode,
        itemCode: row.itemCode,
        itemName: row.itemName
      })
      .then((res: any) => {
        findqiIndexIMainList();
        findqiIndexIMainFilterList();
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
}
// 移除项目
function deleteQiIndexIMainFilter({ row }: any) {
  const url = '/api/qi/reportFiled/deleteQiIndexItemFilter';
  proxy.$http
      .post(url, {
        id: row.id,
        majorCode: selevctBarCodeRow.majorCode,
        indexId: row.indexId,
        indexCode: row.indexCode,
        itemCode: row.itemCode,
        itemName: row.itemName
      })
      .then((res: any) => {
        findqiIndexIMainList();
        findqiIndexIMainFilterList();
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
}
//同步数据
function syncData(){
  syncLoading.value = true;
  const $xTable = proxy.$refs.qiRptFiledTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要同步的项目', VxeNotifyType.warning);
    return;
  }
  //获取selectRows集合,将itemCode和indexCode封装成一个新集合
  const itemList = selectRows.map((item: any) => {
    return {
      indexCode: item.indexCode,
      itemCode: item.itemCode,
      majorCode: selevctBarCodeRow.majorCode
    };
  });
  const url = '/api/qi/reportFiled/syncQiIndexItemData';
  proxy.$http
      .post(url, itemList)
      .then((res: any) => {
        syncLoading.value = false;
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        syncLoading.value = false;
        VxeMessage(err, VxeNotifyType.error);
      });
}

</script>

<style lang="scss" scoped>
#QiRpt {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .qiRptTableBox {
        height: calc(100%);
      }
      .el-tabs {
        height: 100%;
      }
      :deep(.el-tabs__content) {
        height: calc(100%);
        padding: 0;
        .el-tab-pane {
          height: 100%;
        }
      }
      .msgDiv {
        margin-left: 5px;
        color: rgb(180, 28, 28);
      }
    }
  }
  .qiRptFiledTable {
    height: calc(100%);
  }
}
</style>
